package com.example.mvp.Ui.Fragment;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.Nullable;

import com.example.mvp.Model.BaseModel;
import com.example.mvp.Presenter.BasePresenter;
import com.example.mvp.View.BaseView;

public abstract class BaseLazyFragmenter<V extends BaseView,M extends BaseModel,P extends BasePresenter<V,M>> extends BaseFragment{

    private boolean isFirst=false;//第一次加载
    private boolean isUserVisible=false;//不可见
    private boolean isLoading=true;//未加载过数据
    P mPresenter;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        View view=super.onCreateView(inflater, container, savedInstanceState);
        if (view!=null){
            isFirst=true;

        }
        lazyLoad();
        return view;
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser){
            isUserVisible=true;
        }else {
            isUserVisible=false;
        }
        lazyLoad();
    }

    private void lazyLoad() {
        if (isFirst&&isUserVisible&&isLoading){
            mPresenter=cretePresenter();
            if (mPresenter!=null){
                mPresenter.bindView((V)this);
            }
            lazyData();
            isLoading=false;
        }

    }

    protected abstract void lazyData();

    protected abstract P cretePresenter();

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (mPresenter!=null){
            mPresenter.destoryView();
            mPresenter=null;
        }
        isFirst=false;
        isUserVisible=false;
        isLoading=true;
    }
}
